package com.huanzhidadi.single.thread.order;

import java.util.concurrent.Semaphore;

/**
 * Semaphore信号量方式
 */
public class ThreadSemaphore {
    public static void main(String[] args) throws InterruptedException {
        // 初始化Semaphore，设置token总数为1
        Semaphore sem1 = new Semaphore(1);
        Semaphore sem2 = new Semaphore(1);

        // 获取sem1的信号量
        sem1.acquire();
        //获取sem2的信号量
        sem2.acquire();

        // t1不用等待，执行完后释放sem1
        Thread t1 = new Thread(() -> {
            System.out.println("线程t1运行");
            // 释放sem1，允许t2运行
            sem1.release();
        });

        Thread t2 = new Thread(() -> {
            try {
                // 等待sem1
                sem1.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("线程t2运行");
            // 释放sem2，允许t3运行
            sem2.release();
        });

        Thread t3 = new Thread(() -> {
            try {
                // 等待sem2
                sem2.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("线程t3运行");
        });

        t1.start();
        t2.start();
        t3.start();
        System.out.println("主线程完毕");
    }
}
